
/**
 * 重新设置图表初始化
 * @param chart
 * @param option
 * @returns
 */
function setChartOption(chart,option){
	chart.setOption(option,true);
    cfg.current_edit_obj.children(".chartStyle").attr("option",JSON.stringify(option)); 
}

/**
 * 获取echarts对象
 * @returns
 */
function getEchartObj(){
	var current_edit_obj = cfg.current_edit_obj;
	var chart = app.chartMap[current_edit_obj.attr("id")];
	if(chart == null){
		var $chartHtml = current_edit_obj.children(".chartStyle");
		$chartHtml.html("");  
		chart = echarts.init($chartHtml[0]);  
		app.chartMap[current_edit_obj.attr("id")] = chart;
	}
	return chart ;
}

/**
 * 初始化模板地图
 */
function initTemplateMap(id){
	var map = new BMap.Map(id);
    map.enableScrollWheelZoom(true); 
    map.centerAndZoom(new BMap.Point(118.7812,32.0712), 13);
    app.bdMap[id] = map;
}

/**
 * 绑定点击或者时间事件
 */
function initTextOrTime(){
	$("div[nid='0']").each(function(){
		if( $(this).attr("cid") == 6 ){
			;
		}else{
			if( isNotEmpty( $(this).attr("jty")) && isNotEmpty( $(this).attr("jurl"))  ){
				$(this).click(function(){ 
					if( $(this).attr("jty") ==1  ){
						// 弹窗
						layer.open({
						      type: 2,
						      title: ' 设备详情',
				 		      shadeClose: true,
						      shade: 0,
						      maxmin: true, //开启最大化最小化按钮
						      area: ['80%', '80%'],
						      content: $(this).attr("jurl")
						   });
					}else{						
						window.location.href =  $(this).attr("jurl") ;
					}
				})
			}
		}
	})
	setInterval(function() {
		$("div[nid='0']").each(function(){
			if( $(this).attr("cid") == 6 ){
				// 时间控件，则需要定期更新时间
				$(this).find("span").text( timeStamp2String(new Date()) ) ;
			}
		})
	}, 1000);
}

/**
 * 初始化设备状态
 */
function initDeviceStatus(){
	$(".deviceStateNode").each(function(){
		var id = $(this).attr("id");
		var node_id = $(this).attr("node_id") ;
		var that = this ;
		if( node_id != null){
			getAjax(baseurl+'/service/node?id='+node_id,function( res ){
				if( isOK( res )){
					var cmd = gdv( eval('('+ $(that).attr('cmd') +')') , [] );
					var cmdValue = res.data.iot_node_status ;
					for( var i=0; i < cmd.length ; i++ ){
						if( cmdValue >= cmd[i].min && ( (cmd[i].min == cmd[i].max && cmdValue == cmd[i].max   ) || cmdValue < cmd[i].max )){
							$(that).find("img").attr("src" , cmd[i].src );
							$(that).attr("val" , cmdValue ) ;
							break ;
						}
					}
	            }
			}); 
		} 
	})
}

/**
 * 地图初始化
 * @returns
 */
function initMap(){
	$(".mapNode").each(function(){
		var id = $(this).attr("id");
		var node_id = $(this).attr("node_id");
		initTemplateMap(id);
		if(node_id!=null){
			var map = app.bdMap[id]; 
			getAjax(baseurl+'/service/node?id='+node_id,function(e){
				if( isOK(e )){
	                var data=e.data;
	                var lonLat=data.lonLat.split(',')
	                var str_name = 'location2.png' ;
	    			if(data.iot_node_status != 16){
	    				str_name = 'location2_red.png' ;
	    			}
	                var myIcon = new BMap.Icon(baseurl+"/image/oss/iot/"+str_name, new BMap.Size(30,37));
	                var point = new BMap.Point(lonLat[0], lonLat[1]);
	                var marker = new BMap.Marker(point,{icon:myIcon});  // 创建标注
	                map.addOverlay(marker); 
	                map.centerAndZoom(point, 6);              // 将标注添加到地图中
	            }
			}); 
		} 
	})
}

/**
 * 初始化实时数据
 */
function initBaseData(){
	// sensor 动态数据
	initSensorData();
	
	setInterval( function(){
        initSensorData();
	}, 30* 1000);
	
	// 控制节点
	initControlNode();
	initControlNodeClick();
	
	setInterval( function(){
		initControlNode();
	}, 60 * 1000);
	
	// 状态节点
	initStateNode() ;
	
	setInterval( function(){
		initStateNode() ;
	}, 35 * 1000);
	
	setInterval( function() {
		initDeviceStatus();
	}, 20* 1000);
}

/**
 * 绑定事件
 * 
 */
function initControlNodeClick(){
	for( var i=0; i < $("div[nid=9]").length ; i++ ){
		var deviceSensor = $("div[nid=9]").eq(i) ;
		var sensor_id =  deviceSensor.attr("sensor_id") ;
		if(util.isNotEmpty(sensor_id)){
			deviceSensor.click(function(){
				var cmd = gdv( eval('('+ $(this).attr('cmd') +')') , [] );
				var cmdValue = gdv( $(this).attr('val') , 0 ) ;
				for( var i=0; i < cmd.length ; i++ ){
					if( cmdValue >= cmd[i].min && ( (cmd[i].min == cmd[i].max && cmdValue == cmd[i].max ) || cmdValue < cmd[i].max )){
						commonAjax('PUT',baseurl+"/service/sensor/control/realtime/update", {id: $(this).attr("sensor_id") ,request_sdata: cmd[i].send   },function(data){
							app.lastTime = new Date().getTime() - 2*1000 ;
							if(isOK(data)){
								app.$message({
							          message: '成功',
							          type:'success'
							    });
							}else{
								app.$message.error(data.statusMsg);
							}
						});
						break ;
					}
				}
			 })
		}
	}
	
	// 配置下发组件
	for( var i=0; i < $("div[nid=1][cid=11]").length ; i++ ){
		var deviceSensor = $("div[nid=1][cid=11]").eq(i) ;
		var sensor_id =  deviceSensor.attr("sensor_id") ;
		if(util.isNotEmpty(sensor_id)){
			deviceSensor.click(function(){
				// -- 
				app.dialogVisible = true ;
				app.downSensorId = $(this).attr("sensor_id") ;
			})
		}
	}
	
}


/**
 * 控制
 * @returns
 */
function initControlNode(){
	for( var i=0; i < $("div[nid=9]").length ; i++ ){
		var sensor_id =  $("div[nid=9]").eq(i).attr("sensor_id") ;
		if(util.isNotEmpty(sensor_id)){
			getAjax(baseurl+'/service/sensor?id='+sensor_id,function(res){
				if( isOK(res) ){
					var objs =  $("div[nid=9][sensor_id="+ res.data.id +"]") ;
					for(var k=0;k< objs.length ;k++){
						var obj = objs.eq(k)  ;
						var cmd = gdv( eval('('+ obj.attr('cmd') +')') , [] );
						var cmdValue = res.data.sdata ;
						for( var i=0; i < cmd.length ; i++ ){
							if( cmdValue >= cmd[i].min && ( (cmd[i].min == cmd[i].max && cmdValue == cmd[i].max   ) || cmdValue < cmd[i].max )){
								obj.find("img").attr("src" , cmd[i].src );
								obj.attr("val" , cmdValue ) ;
								break ;
							}
						}						
					}
				}
			});	
		}
	}
}

/**
 * 状态初始化
 */
function initStateNode(){
	for( var i=0; i < $("div[nid=8]").length ; i++ ){
		var sensor_id =  $("div[nid=8]").eq(i).attr("sensor_id") ;
		if(util.isNotEmpty(sensor_id)){
			getAjax(baseurl+'/service/sensor?id='+sensor_id,function(res){
				if( isOK(res) ){
					var objs =  $("div[nid=8][sensor_id="+ res.data.id +"]") ;
					for(var k=0;k< objs.length ;k++){
						var obj = objs.eq(k) ;
						
						var cmd = gdv( eval('('+ obj.attr('cmd') +')') , [] );
						var cmdValue = res.data.sdata ;
						for( var i=0; i < cmd.length ; i++ ){
							if( cmdValue >= cmd[i].min && ( (cmd[i].min == cmd[i].max && cmdValue == cmd[i].max) || cmdValue < cmd[i].max )){
								obj.find("img").attr("src" , cmd[i].src );
								break ;
							}
						}						
					}
				}
			});	
		}
	}
}

/**
 * 数据初始化
 */
function initSensorData(){
	// nid = 1 传感器动态数据
	for( var i=0; i < $("div[nid=1]").length ; i++ ){
		var sensor_id =  $("div[nid=1]").eq(i).attr("sensor_id") ;
		if(util.isNotEmpty(sensor_id)){
			getAjax(baseurl+'/service/sensor?id='+sensor_id,function(res){
				if( isOK(res) ){
					if( util.isNotEmpty(  $("div[nid=1][sensor_id="+ res.data.id +"]").eq(0).attr("cid")  ) ){
						if(  $("div[nid=1][sensor_id="+ res.data.id +"]").eq(0).attr("cid") == 7 ){
							$("div[nid=1][sensor_id="+ res.data.id +"]").find(".canvas_text").html(res.data.data.measure_unit_type) ;							
						}else if( $("div[nid=1][sensor_id="+ res.data.id +"]").eq(0).attr("cid") == 11 ){
							$("div[nid=1][sensor_id="+ res.data.id +"]").find(".canvas_text").html(res.data.sdata) ;
						}
					}else{
						$("div[nid=1][sensor_id="+ res.data.id +"]").find(".canvas_text").html(res.data.sdata) ;	
					}
				}
			});			
		}
	}
}

/**
 * 视频初始化
 * @returns
 */
function initVideo(){
	$(".videoNode").each(function(){
		var video_url = $(this).attr("video_info");

		var ninfo = $(this).attr("id");
		// var player = new EZUIPlayer(  ninfo.replace("node","video_") );

		let webRtcServer = new WebRtcStreamer(ninfo.replace("node","video_"), location.protocol + '//137.50.95.240:8000')
		//需要查看的rtsp地址
		webRtcServer.connect(video_url)
		// player.on('error', function(){
		//    console.log('error');
		// });
		// player.on('play', function(){
		//    console.log('play');
		// });
		// player.on('pause', function(){
		//    console.log('pause');
		// });
	})
}

/**
 * 第一次进入的时候重新初始化chart对象  
 * 取标签中的option属性重新初始化
 * @returns
 */
function reinitChartObj(){
	var chartMap = app.chartMap;
	$(".chartStyle").each(function(){
		var id = $(this).parent().attr("id");
		var cid = $(this).parent().attr("cid");
		if(cid == 4){
			var json = $(this).attr("option");
			var myChart = echarts.init($(this)[0]);
			var option = JSON.parse(json) ;
			option.series[0].data = [{name:'sensor',value:0}];
			myChart.setOption(option);
			app.chartMap[id] = myChart;
		}else if(cid == 10){
			var json = $(this).attr("option");
			var myChart = echarts.init($(this)[0]);
			var option = JSON.parse(json) ;
			option.series[0].effect.show = false ;
			myChart.setOption(option);
			app.chartMap[id] = myChart;
			
		}else if(id != null){
			var json = $(this).attr("option");
			var myChart = echarts.init($(this)[0]);
			var option = JSON.parse(json) ;
			if( option.xAxis != null )
				option.xAxis.data = [] ;
			option.series[0].data = [] ;
			myChart.setOption(JSON.parse(json),true);
			app.chartMap[id] = myChart;
		}
	})
	// 初始化列表
	refleshSensorList() ;
}

/**
 * 列表数据初始化
 */
function refleshSensorList(){
	$(".chartStyle").each(function(){
		var id = $(this).parent().attr("id");
		var sensor_id = $(this).parent().attr("sensor_id");
		var cid = $(this).parent().attr("cid") ;
		var max = $(this).parent().attr("max") ;
		var that = this ;

		if(id != null && sensor_id != null ){
			if(cid == 3){
				// 仪表盘
				getAjax(baseurl+'/service/sensor?id='+sensor_id,function(res){
					if( isOK(res) ){
						app.chartMap[id].setOption({
							series: [{
								data: [{value:res.data.sdata , name:res.data.name }]
							}]
						});
			        }
				});
			}else if(cid == 4){
				// 液位图
				getAjax(baseurl+'/service/sensor?id='+sensor_id,function(res){
					if( isOK(res) ){
						app.chartMap[id].setOption({
							series: [{
								data: [ {name:'sensor',value:res.data.sdata/max }  ]
							}]
						});
			        }
				});
			}else if(cid == 10){
				// 管道图
				getAjax(baseurl+'/service/sensor?id='+sensor_id,function(res){
					if( isOK(res) ){
						var json = $(that).attr("option");
						var option = JSON.parse(json) ;
						option.series[0].effect.show = res.data.sdata>0  ;
						app.chartMap[id].setOption(option);
			        }
				});
			}else{
				commonAjax("POST",baseurl+"/service/page/sensor/history?paged=1&pageSize=20", { sensor_id: sensor_id },function(res){
					var x_data = [];
					var y_data = [];
					if(isOK(res)){
						var datat= res.data.data;
						for (var i = datat.length-1 ; i >= 0; i--) {
							x_data.push( datat[i].atimestr);
							y_data.push( datat[i].sdata );
						}
					}
					app.chartMap[id].x_data = x_data ;
					app.chartMap[id].y_data = y_data ;
					app.chartMap[id].setOption({
						xAxis: {
							data: x_data
						},
						series: [{
							data: y_data
						}]
					});
				});				
			}
		}
	})	
}

/**
 * 图表数据更新
 */
function udpChartValue(){
	$(".chartStyle").each(function(){
		var id = $(this).parent().attr("id");
		var sensor_id = $(this).parent().attr("sensor_id");
		var cid = $(this).parent().attr("cid") ;
		var max = $(this).parent().attr("max") ;
		var that = this ;
		if(id != null && sensor_id != null ){
			getAjax(baseurl+'/service/sensor?id='+sensor_id,function(res){
				if( isOK(res) ){
					if( cid == 3 ){
						// 表盘类型
						app.chartMap[id].setOption({
							series: [{
								data: [{value:res.data.sdata , name:res.data.name }]
							}]
						});
					}else if(cid == 4){
						// 液位图
						app.chartMap[id].setOption({
							series: [{
								data: [ {name:res.data.name , value:res.data.sdata/max }  ]
							}]
						});
					}else if(cid == 10){
						// 管道图
						var json = $(that).attr("option");
						var option = JSON.parse(json) ;
						option.series[0].effect.show = res.data.sdata>0  ;
						app.chartMap[id].setOption(option);
					}else{
						// 曲线类型
						var x_data = app.chartMap[id].x_data;
						var y_data = app.chartMap[id].y_data;
						if( x_data.length >0  ){
							var tmpx = x_data[ x_data.length -1 ] ;
							var tmpy = y_data[ y_data.length -1 ] ;
							var sensorData = timeStamp2String( res.data.mtime,'yyyy-MM-dd hh:mm:ss') ;
						
							if(sensorData  != tmpx ){
								x_data.shift();
								y_data.shift();
								x_data.push( sensorData);
								y_data.push( res.data.sdata );
							}
							app.chartMap[id].x_data = x_data ;
							app.chartMap[id].y_data = y_data ;
							app.chartMap[id].setOption({
								xAxis: {
									data: x_data
								},
								series: [{
									data: y_data
								}]
							});
						}
					}
		        }
			});
		}
	})
}

function scaled(){
	app.changescaler = app.changescaler + 0.1  ;
	var xr = app.changescaler ;
	var win_width = $(window).width() ;
	var win_height = $(window).height() ;
	
	var xwidth = 0 ;
	var xheight = 0 ;
	
	if(xr < 1  && app.scaler != 1 ){
		xwidth = (win_width - app.orginWidth  * xr)/2/xr  ;
		xheight = (win_height - app.orginHeight * xr)/2/xr ;		
	}
	
	xwidth = xwidth>0?xwidth:0 ;
	xheight = xheight>0?xheight:0 ;
	
	$(".edit-container").css({
   		"-webkit-transform":"scale(" + xr + ", "+ xr +" ) translate("+xwidth+"px,"+xheight+"px)",
   		"transform":"scale(" + xr + ", "+ xr +" ) translate("+xwidth+"px,"+xheight+"px)"
   	});
}
function scalex(){
	if(app.changescaler<0.39){
		return ;
	}
	app.changescaler = app.changescaler - 0.1  ;
	var xr = app.changescaler ;
	
	var win_width = $(window).width() ;
	var win_height = $(window).height() ;
	
	var xwidth = 0 ;
	var xheight = 0 ;
	
	if(xr < 1  && app.scaler != 1   ){
		xwidth = (win_width - app.orginWidth  * xr)/2/xr  ;
		xheight = (win_height - app.orginHeight * xr)/2/xr ;		
	}
	
	xwidth = xwidth>0?xwidth:0 ;
	xheight = xheight>0?xheight:0 ;
	
	$(".edit-container").css({
   		"-webkit-transform":"scale(" + xr + ", "+ xr +" ) translate("+xwidth+"px,"+xheight+"px)",
   		"transform":"scale(" + xr + ", "+ xr +" ) translate("+xwidth+"px,"+xheight+"px)"
   	});
}
function scalen(){
	var xr = app.scaler   ;
	
	xwidth = 0 ;
	xheight = 0 ;
	
	$(".edit-container").css({
   		"-webkit-transform":"scale(" + xr + ", "+ xr +" ) translate("+xwidth+"px,"+xheight+"px)",
   		"transform":"scale(" + xr + ", "+ xr +" ) translate("+xwidth+"px,"+xheight+"px)"
   	});
}

//
//----------基础方法-----------------------------------------------------------------------------
//

function tip(content,time,func){
	if(content == undefined){
		content = "error";
	}
	try{
		if( time==null || time == '' )
			time = 1200 ;
		if( func==null )
			layer.msg(content,{time:time});
		else{
			layer.msg(content,{time:time},function(){
				func();
			});
		}		
	}catch(e){
	}
};

function getAjax(url, sucessCallBack, errorCallBack) {
	if(typeof(ucode)=="undefined"){
		ucode='';
	}
	$.ajax({
		type : "GET",
		url : url,
		contentType : "application/json",
		dataType : "json",
		async : true,
		headers : {
			'USER-KEY' :ucode 
		},
		success : function(data){
			sucessCallBack(data);
		},
		error : errorCallBack
	})
};

var isOk= isOK ;
function isOK(e){
	if(e.status == 2 ){
		return true ;
	}else{
		return false ;
	}
}

function isNotEmpty(val){
	if(val!=null && val!=''){
		return true ;
	}else{
		return false ;
	}
}
